<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>2D沙盒世界 - 修复版</title>
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
            font-family: 'Courier New', monospace;
            touch-action: none;
        }
        
        body {
            background: #000;
            color: #ccc;
            overflow: hidden;
            height: 100vh;
            width: 100vw;
            display: flex;
            justify-content: center;
            align-items: center;
        }
        
        #gameContainer {
            position: relative;
            width: 100%;
            height: 100%;
            max-width: 100%;
            max-height: 100%;
            overflow: hidden;
        }
        
        #mainMenu, #gameScreen {
            position: absolute;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            display: flex;
            flex-direction: column;
            justify-content: center;
            align-items: center;
            background: #000;
        }
        
        #gameScreen {
            display: none;
        }
        
        .title {
            font-size: 24px;
            margin-bottom: 30px;
            text-align: center;
            color: #ccc;
        }
        
        .menu-btn {
            width: 200px;
            padding: 10px;
            margin: 10px;
            background: #000;
            border: 2px solid #ccc;
            color: #ccc;
            font-size: 16px;
            cursor: pointer;
            text-align: center;
        }
        
        .menu-btn:hover {
            background: #333;
            color: #fff;
        }
        
        #seedInput {
            width: 200px;
            padding: 10px;
            margin: 10px;
            background: #000;
            border: 2px solid #ccc;
            color: #ccc;
            font-size: 16px;
            text-align: center;
        }
        
        #worldList {
            width: 200px;
            max-height: 150px;
            overflow-y: auto;
            margin: 10px;
            border: 1px solid #ccc;
        }
        
        .world-item {
            padding: 8px;
            border-bottom: 1px solid #ccc;
            cursor: pointer;
            font-size: 12px;
            color: #ccc;
        }
        
        .world-item:hover {
            background: #333;
            color: #fff;
        }
        
        #gameCanvas {
            background: #000;
            width: 100%;
            height: 100%;
            display: block;
            image-rendering: pixelated;
        }
        
        #uiContainer {
            position: absolute;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            pointer-events: none;
        }
        
        /* WASD控件在左下方 */
        #wasdControls {
            position: absolute;
            bottom: 120px;
            left: 50px;
            width: 120px;
            height: 120px;
            pointer-events: auto;
            display: grid;
            grid-template-columns: repeat(3, 1fr);
            grid-template-rows: repeat(3, 1fr);
            gap: 5px;
        }
        
        .wasd-btn {
            background: rgba(0, 0, 0, 0.5);
            border: 2px solid #ccc;
            color: #ccc;
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: 18px;
            cursor: pointer;
            user-select: none;
        }
        
        .wasd-btn:active {
            background: rgba(204, 204, 204, 0.3);
        }
        
        #hotbar {
            position: absolute;
            bottom: 20px;
            left: 50%;
            transform: translateX(-50%);
            display: flex;
            gap: 3px;
            background: rgba(0, 0, 0, 0.7);
            padding: 3px;
            border: 2px solid #ccc;
            pointer-events: auto;
        }
        
        .hotbarSlot {
            width: 30px;
            height: 30px;
            background: rgba(204, 204, 204, 0.2);
            border: 1px solid #ccc;
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: 14px;
            cursor: pointer;
            color: #ccc;
        }
        
        .hotbarSlot.active {
            background: rgba(204, 204, 204, 0.5);
        }
        
        /* 修改背包为四行八列 */
        #inventory {
            position: absolute;
            top: 50%;
            left: 50%;
            transform: translate(-50%, -50%);
            background: rgba(0, 0, 0, 0.9);
            padding: 15px;
            border: 2px solid #ccc;
            display: none;
            grid-template-columns: repeat(8, 30px);
            grid-template-rows: repeat(4, 30px);
            grid-gap: 3px;
            pointer-events: auto;
            z-index: 10;
        }
        
        .inventorySlot {
            width: 30px;
            height: 30px;
            background: rgba(204, 204, 204, 0.2);
            border: 1px solid #ccc;
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: 14px;
            cursor: pointer;
            color: #ccc;
        }
        
        /* 第一行加粗 */
        .inventorySlot:nth-child(-n+8) {
            border-width: 2px;
        }
        
        .inventorySlot:hover {
            background: rgba(204, 204, 204, 0.4);
        }
        
        .inventorySlot.selected {
            border: 2px solid #ffcc00;
        }
        
        #menu {
            position: absolute;
            bottom: 20px;
            right: 20px;
            display: flex;
            gap: 5px;
            pointer-events: auto;
        }
        
        .game-btn {
            padding: 5px 10px;
            font-size: 12px;
            background: #000;
            border: 2px solid #ccc;
            color: #ccc;
            cursor: pointer;
        }
        
        .game-btn:hover {
            background: #333;
            color: #fff;
        }
        
        #debugInfo {
            position: absolute;
            top: 10px;
            left: 10px;
            background: rgba(0, 0, 0, 0.7);
            padding: 5px;
            border: 2px solid #ccc;
            font-size: 10px;
            line-height: 1.3;
            color: #ccc;
        }
        
        #worldName {
            position: absolute;
            top: 10px;
            left: 50%;
            transform: translateX(-50%);
            background: rgba(0, 0, 0, 0.7);
            padding: 5px 10px;
            border: 2px solid #ccc;
            font-size: 12px;
            text-align: center;
            color: #ccc;
        }
        
        #zoomControls {
            position: absolute;
            top: 10px;
            right: 10px;
            display: flex;
            flex-direction: column;
            gap: 5px;
            pointer-events: auto;
        }
        
        .zoom-btn {
            width: 40px;
            height: 40px;
            background: rgba(0, 0, 0, 0.7);
            border: 2px solid #ccc;
            color: #ccc;
            font-size: 20px;
            display: flex;
            align-items: center;
            justify-content: center;
            cursor: pointer;
        }
        
        .zoom-btn:hover {
            background: #333;
        }
        
        #modManager {
            position: absolute;
            top: 50%;
            left: 50%;
            transform: translate(-50%, -50%);
            background: rgba(0, 0, 0, 0.9);
            padding: 20px;
            border: 2px solid #ccc;
            display: none;
            flex-direction: column;
            gap: 10px;
            width: 300px;
            z-index: 20;
            pointer-events: auto;
        }
        
        .mod-item {
            display: flex;
            justify-content: space-between;
            align-items: center;
            padding: 10px;
            border: 1px solid #ccc;
        }
        
        .mod-name {
            font-size: 14px;
        }
        
        .mod-toggle {
            position: relative;
            width: 50px;
            height: 24px;
        }
        
        .mod-toggle input {
            opacity: 0;
            width: 0;
            height: 0;
        }
        
        .mod-slider {
            position: absolute;
            cursor: pointer;
            top: 0;
            left: 0;
            right: 0;
            bottom: 0;
            background-color: #333;
            transition: .4s;
            border-radius: 24px;
        }
        
        .mod-slider:before {
            position: absolute;
            content: "";
            height: 16px;
            width: 16px;
            left: 4px;
            bottom: 4px;
            background-color: #ccc;
            transition: .4s;
            border-radius: 50%;
        }
        
        input:checked + .mod-slider {
            background-color: #006600;
        }
        
        input:checked + .mod-slider:before {
            transform: translateX(26px);
        }
        
        #modBtn {
            position: absolute;
            top: 20px;
            right: 20px;
            padding: 5px 10px;
            font-size: 12px;
            background: #000;
            border: 2px solid #ccc;
            color: #ccc;
            cursor: pointer;
        }
        
        #modBtn:hover {
            background: #333;
            color: #fff;
        }
        
        /* 添加显示方块分界线的开关 */
        #gridToggle {
            position: absolute;
            bottom: 20px;
            left: 200px;
            padding: 5px 10px;
            font-size: 12px;
            background: #000;
            border: 2px solid #ccc;
            color: #ccc;
            cursor: pointer;
            pointer-events: auto;
        }
        
        #gridToggle:hover {
            background: #333;
            color: #fff;
        }
        
        #gridToggle.active {
            background: #333;
            border-color: #ffcc00;
        }
    </style>
</head>
<body>
    <div id="gameContainer">
        <div id="mainMenu">
            <h1 class="title">2D沙盒世界 - 修复版</h1>
            <input type="text" id="seedInput" placeholder="世界种子 (可选)">
            <div id="worldList">
                <!-- 世界列表将通过JS动态生成 -->
            </div>
            <button id="newWorldBtn" class="menu-btn">创建新世界</button>
            <button id="loadWorldBtn" class="menu-btn">加载世界</button>
            <button id="modBtn" class="menu-btn">MOD管理</button>
        </div>
        
        <div id="gameScreen">
            <canvas id="gameCanvas"></canvas>
            <div id="uiContainer">
                <div id="worldName">新世界</div>
                
                <div id="debugInfo">
                    <div>坐标: (0, 0)</div>
                    <div>区块: (0, 0)</div>
                    <div>生物群系: 平原</div>
                    <div>缩放: 200%</div>
                </div>
                
                <div id="zoomControls">
                    <div class="zoom-btn" id="zoomInBtn">+</div>
                    <div class="zoom-btn" id="zoomOutBtn">-</div>
                </div>
                
                <div id="menu">
                    <button id="inventoryBtn" class="game-btn">背包</button>
                    <button id="saveBtn" class="game-btn">保存</button>
                    <button id="menuBtn" class="game-btn">菜单</button>
                </div>
                
                <!-- WASD控件在左下方 -->
                <div id="wasdControls">
                    <div class="wasd-btn" style="grid-column: 2; grid-row: 1;" id="wBtn">W</div>
                    <div class="wasd-btn" style="grid-column: 1; grid-row: 2;" id="aBtn">A</div>
                    <div class="wasd-btn" style="grid-column: 2; grid-row: 2;" id="sBtn">S</div>
                    <div class="wasd-btn" style="grid-column: 3; grid-row: 2;" id="dBtn">D</div>
                </div>
                
                <!-- 添加显示方块分界线的开关 -->
                <button id="gridToggle" class="game-btn">网格: 关</button>
                
                <div id="hotbar">
                    <!-- 快捷栏将通过JS动态生成 -->
                </div>
                
                <!-- 修改背包为四行八列 -->
                <div id="inventory">
                    <!-- 背包格子将通过JS动态生成 -->
                </div>
            </div>
        </div>
        
        <div id="modManager">
            <h3>MOD管理</h3>
            <div id="modList">
                <!-- MOD列表将通过JS动态生成 -->
            </div>
            <button id="closeModBtn" class="menu-btn">关闭</button>
        </div>
    </div>

    <script>
        // 游戏配置
        const config = {
            chunkSize: 16,
            tileSize: 32,
            renderDistance: 5,
            moveSpeed: 3, // 角色移动速度改为3方块每秒
            biomeSize: 16,
            joystickRadius: 50,
            minZoom: 0.5,
            maxZoom: 3.0,
            defaultZoom: 2.0, // 默认放大倍数改为200%
            zoomStep: 0.5,
            allowedZooms: [0.5, 1.0, 1.5, 2.0, 2.5, 3.0],
            buildingDensity: 0.2
        };

        // 建筑类型定义
        const BUILDINGS = {
            GRASS: {
                name: 'grass',
                emoji: '🌿',
                width: 1,
                height: 1,
                hasCollision: false,
                spawnBiomes: ['grass', 'forest'],
                spawnChances: {
                    'grass': 0.2,
                    'forest': 0.15
                }
            },
            TREE: {
                name: 'tree',
                emoji: '🌳',
                width: 1,
                height: 2,
                hasCollision: true,
                collisionHeight: 1,
                spawnBiomes: ['grass', 'forest'],
                spawnChances: {
                    'grass': 0.05,
                    'forest': 0.15
                }
            }
        };

        // 游戏状态
        const gameState = {
            player: {
                x: 0,
                y: 0,
                velocityX: 0,
                velocityY: 0
            },
            chunks: {},
            buildings: {},
            inventory: {
                items: Array(32).fill(null), // 32个格子 (4行×8列)
                hotbar: Array(8).fill(null),
                selectedSlot: 0,
                selectedItem: null
            },
            isInventoryOpen: false,
            worldName: "新世界",
            worldSeed: Date.now(),
            isMoving: false,
            wasdActive: {
                w: false,
                a: false,
                s: false,
                d: false
            },
            zoomLevel: config.defaultZoom,
            mods: {
                natureMod: true,
                buildingMod: false,
                monsterMod: false,
                crystalMod: true // 添加水晶MOD状态
            },
            // 添加性能优化相关状态
            lastChunkUpdate: 0,
            chunkUpdateInterval: 500,
            visibleChunks: new Set(),
            lastRenderTime: 0,
            frameCount: 0,
            fps: 0,
            // 添加显示网格状态
            showGrid: false
        };

        // 内存存档系统
        const memoryStorage = {
            worlds: [],
            saveWorld: function(worldData) {
                const index = this.worlds.findIndex(w => w.name === worldData.name);
                if (index !== -1) {
                    this.worlds[index] = worldData;
                } else {
                    this.worlds.push(worldData);
                }
            },
            loadWorld: function(name) {
                return this.worlds.find(w => w.name === name);
            },
            getWorldList: function() {
                return this.worlds.map(w => ({ name: w.name, seed: w.seed }));
            }
        };

        // ==================== MOD模块接口开始 ====================
        // 当前已安装的MOD列表
        const installedMods = [
          // ==================== 水晶矿MOD开始 ====================
          {
            name: "水晶矿MOD",
            id: "crystalMod",
            version: "1.0",
            author: "沙盒世界开发者",
            description: "添加水晶矿资源，可在山地生物群系中找到",
            
            init: function() {
              console.log("水晶矿MOD已初始化");
              
              // 将水晶矿添加到建筑定义中
              Object.assign(BUILDINGS, this.buildings);
            },
            
            buildings: {
              CRYSTAL: {
                name: 'crystal',
                emoji: '💎',
                width: 1,
                height: 1,
                hasCollision: true,
                spawnBiomes: ['mountain'],
                spawnChances: {
                  'mountain': 0.05
                }
              }
            },
            
            items: {
              CRYSTAL: {
                name: '水晶',
                icon: '💎',
                description: '闪闪发光的水晶矿石'
              }
            }
          }
          // ==================== 水晶矿MOD结束 ====================
        ];

        // MOD系统初始化函数
        function initModSystem() {
          installedMods.forEach(mod => {
            try {
              if (mod.init && typeof mod.init === 'function') {
                mod.init();
              }
              
              // 扩展建筑系统
              if (mod.buildings) {
                Object.assign(BUILDINGS, mod.buildings);
              }
              
              console.log(`MOD "${mod.name}" 已加载`);
            } catch (error) {
              console.error(`加载MOD "${mod.name}" 时出错:`, error);
            }
          });
        }
        // ==================== MOD模块接口结束 ====================

        // MOD系统
        const modSystem = {
            natureMod: {
                activate: function() { 
                    console.log("自然扩展MOD已激活"); 
                },
                deactivate: function() { 
                    console.log("自然扩展MOD已禁用"); 
                },
                modifyBiomeGeneration: function(noiseValue) {
                    if (noiseValue < -0.4) return 'water';
                    if (noiseValue < -0.2) return 'sand';
                    if (noiseValue < 0.0) return 'grass';
                    if (noiseValue < 0.2) return 'forest';
                    if (noiseValue < 0.4) return 'mountain';
                    if (gameState.mods.natureMod) {
                        if (noiseValue < 0.6) return 'snow';
                        if (noiseValue < 0.8) return 'desert';
                        return 'jungle';
                    }
                    return 'mountain';
                },
                getBiomeColor: function(biome) {
                    const colors = {
                        'snow': '#ffffff',
                        'desert': '#ffcc66',
                        'jungle': '#009900'
                    };
                    return colors[biome] || null;
                },
                getBiomeDisplayName: function(biome) {
                    const names = {
                        'snow': '雪地',
                        'desert': '沙漠',
                        'jungle': '丛林'
                    };
                    return names[biome] || null;
                }
            },
            
            buildingMod: {
                activate: function() { console.log("建筑MOD已激活"); },
                deactivate: function() { console.log("建筑MOD已禁用"); }
            },
            
            monsterMod: {
                activate: function() { console.log("怪物MOD已激活"); },
                deactivate: function() { console.log("怪物MOD已禁用"); }
            },
            
            crystalMod: {
                activate: function() { console.log("水晶矿MOD已激活"); },
                deactivate: function() { console.log("水晶矿MOD已禁用"); }
            },
            
            initMods: function() {
                if (gameState.mods.natureMod) this.natureMod.activate();
                if (gameState.mods.buildingMod) this.buildingMod.activate();
                if (gameState.mods.monsterMod) this.monsterMod.activate();
                if (gameState.mods.crystalMod) this.crystalMod.activate();
            }
        };

        // 获取DOM元素
        const mainMenu = document.getElementById('mainMenu');
        const gameScreen = document.getElementById('gameScreen');
        const canvas = document.getElementById('gameCanvas');
        const ctx = canvas.getContext('2d');
        const debugInfo = document.getElementById('debugInfo');
        const inventoryBtn = document.getElementById('inventoryBtn');
        const inventory = document.getElementById('inventory');
        const hotbar = document.getElementById('hotbar');
        const newWorldBtn = document.getElementById('newWorldBtn');
        const loadWorldBtn = document.getElementById('loadWorldBtn');
        const seedInput = document.getElementById('seedInput');
        const worldNameElement = document.getElementById('worldName');
        const menuBtn = document.getElementById('menuBtn');
        const saveBtn = document.getElementById('saveBtn');
        const worldList = document.getElementById('worldList');
        const zoomInBtn = document.getElementById('zoomInBtn');
        const zoomOutBtn = document.getElementById('zoomOutBtn');
        const modBtn = document.getElementById('modBtn');
        const modManager = document.getElementById('modManager');
        const modList = document.getElementById('modList');
        const closeModBtn = document.getElementById('closeModBtn');
        const wBtn = document.getElementById('wBtn');
        const aBtn = document.getElementById('aBtn');
        const sBtn = document.getElementById('sBtn');
        const dBtn = document.getElementById('dBtn');
        const gridToggle = document.getElementById('gridToggle');

        // 初始化Canvas大小
        function resizeCanvas() {
            canvas.width = gameScreen.clientWidth;
            canvas.height = gameScreen.clientHeight;
        }

        // 初始化游戏
        function init() {
            resizeCanvas();
            
            // 初始化MOD系统
            initModSystem();
            
            // 初始化MOD系统 (旧版本)
            modSystem.initMods();
            
            // 初始化背包和快捷栏UI
            initInventory();
            initHotbar();
            
            // 生成初始区块
            generateInitialChunks();
            
            // 设置事件监听器
            setupEventListeners();
            
            // 开始游戏循环
            gameLoop();
        }

        // 初始化背包 - 改为4行8列
        function initInventory() {
            inventory.innerHTML = '';
            for (let i = 0; i < 32; i++) {
                const slot = document.createElement('div');
                slot.className = 'inventorySlot';
                slot.dataset.index = i;
                
                // 添加一些示例物品
                if (i < 8) {
                    const icons = ['🌱', '🌳', '💧', '🪨', '🏠', '🔥', '❄️', '⚡'];
                    slot.textContent = icons[i];
                    gameState.inventory.items[i] = {
                        icon: icons[i],
                        name: ['草方块', '树木', '水', '石头', '房屋', '火', '冰', '闪电'][i]
                    };
                }
                
                slot.addEventListener('click', () => handleInventorySlotClick(i));
                inventory.appendChild(slot);
            }
        }

        // 初始化快捷栏
        function initHotbar() {
            hotbar.innerHTML = '';
            for (let i = 0; i < 8; i++) {
                const slot = document.createElement('div');
                slot.className = 'hotbarSlot';
                if (i === 0) slot.classList.add('active');
                slot.dataset.index = i;
                
                if (gameState.inventory.items[i]) {
                    slot.textContent = gameState.inventory.items[i].icon;
                    gameState.inventory.hotbar[i] = gameState.inventory.items[i];
                }
                
                slot.addEventListener('click', () => selectHotbarSlot(i));
                hotbar.appendChild(slot);
            }
        }

        // 处理背包格子点击
        function handleInventorySlotClick(index) {
            const slot = document.querySelector(`.inventorySlot[data-index="${index}"]`);
            
            if (gameState.inventory.selectedItem === null) {
                if (gameState.inventory.items[index]) {
                    gameState.inventory.selectedItem = index;
                    slot.classList.add('selected');
                }
            } else {
                const selectedIndex = gameState.inventory.selectedItem;
                const temp = gameState.inventory.items[selectedIndex];
                gameState.inventory.items[selectedIndex] = gameState.inventory.items[index];
                gameState.inventory.items[index] = temp;
                
                updateInventorySlot(selectedIndex);
                updateInventorySlot(index);
                
                if (selectedIndex < 8) updateHotbarSlot(selectedIndex);
                if (index < 8) updateHotbarSlot(index);
                
                gameState.inventory.selectedItem = null;
                document.querySelectorAll('.inventorySlot').forEach(s => {
                    s.classList.remove('selected');
                });
            }
        }

        // 更新单个背包格子
        function updateInventorySlot(index) {
            const slot = document.querySelector(`.inventorySlot[data-index="${index}"]`);
            if (!slot) return;
            
            const item = gameState.inventory.items[index];
            slot.textContent = item ? item.icon : '';
        }

        // 更新单个快捷栏格子
        function updateHotbarSlot(index) {
            const slot = document.querySelector(`.hotbarSlot[data-index="${index}"]`);
            if (!slot) return;
            
            const item = gameState.inventory.items[index];
            slot.textContent = item ? item.icon : '';
            gameState.inventory.hotbar[index] = item;
        }

        // 设置事件监听器
        function setupEventListeners() {
            // WASD控制事件
            setupWASDControls();
            
            // 键盘控制事件
            setupKeyboardControls();
            
            // 背包按钮
            inventoryBtn.addEventListener('click', toggleInventory);
            
            // 主菜单按钮
            newWorldBtn.addEventListener('click', createNewWorld);
            loadWorldBtn.addEventListener('click', loadWorld);
            menuBtn.addEventListener('click', showMainMenu);
            saveBtn.addEventListener('click', saveWorld);
            
            // MOD按钮
            modBtn.addEventListener('click', showModManager);
            closeModBtn.addEventListener('click', hideModManager);
            
            // 缩放控制按钮
            zoomInBtn.addEventListener('click', () => zoomIn());
            zoomOutBtn.addEventListener('click', () => zoomOut());
            
            // 添加网格开关事件
            gridToggle.addEventListener('click', toggleGrid);
            
            // 初始化世界列表
            initWorldList();
            
            // 窗口大小变化监听
            window.addEventListener('resize', resizeCanvas);
        }

        // 设置WASD控制
        function setupWASDControls() {
            // W键
            wBtn.addEventListener('mousedown', () => {
                gameState.wasdActive.w = true;
                updateMovement();
            });
            wBtn.addEventListener('mouseup', () => {
                gameState.wasdActive.w = false;
                updateMovement();
            });
            wBtn.addEventListener('mouseleave', () => {
                gameState.wasdActive.w = false;
                updateMovement();
            });
            
            // A键
            aBtn.addEventListener('mousedown', () => {
                gameState.wasdActive.a = true;
                updateMovement();
            });
            aBtn.addEventListener('mouseup', () => {
                gameState.wasdActive.a = false;
                updateMovement();
            });
            aBtn.addEventListener('mouseleave', () => {
                gameState.wasdActive.a = false;
                updateMovement();
            });
            
            // S键
            sBtn.addEventListener('mousedown', () => {
                gameState.wasdActive.s = true;
                updateMovement();
            });
            sBtn.addEventListener('mouseup', () => {
                gameState.wasdActive.s = false;
                updateMovement();
            });
            sBtn.addEventListener('mouseleave', () => {
                gameState.wasdActive.s = false;
                updateMovement();
            });
            
            // D键
            dBtn.addEventListener('mousedown', () => {
                gameState.wasdActive.d = true;
                updateMovement();
            });
            dBtn.addEventListener('mouseup', () => {
                gameState.wasdActive.d = false;
                updateMovement();
            });
            dBtn.addEventListener('mouseleave', () => {
                gameState.wasdActive.d = false;
                updateMovement();
            });
            
            // 触摸设备支持
            wBtn.addEventListener('touchstart', (e) => {
                e.preventDefault();
                gameState.wasdActive.w = true;
                updateMovement();
            });
            wBtn.addEventListener('touchend', (e) => {
                e.preventDefault();
                gameState.wasdActive.w = false;
                updateMovement();
            });
            
            aBtn.addEventListener('touchstart', (e) => {
                e.preventDefault();
                gameState.wasdActive.a = true;
                updateMovement();
            });
            aBtn.addEventListener('touchend', (e) => {
                e.preventDefault();
                gameState.wasdActive.a = false;
                updateMovement();
            });
            
            sBtn.addEventListener('touchstart', (e) => {
                e.preventDefault();
                gameState.wasdActive.s = true;
                updateMovement();
            });
            sBtn.addEventListener('touchend', (e) => {
                e.preventDefault();
                gameState.wasdActive.s = false;
                updateMovement();
            });
            
            dBtn.addEventListener('touchstart', (e) => {
                e.preventDefault();
                gameState.wasdActive.d = true;
                updateMovement();
            });
            dBtn.addEventListener('touchend', (e) => {
                e.preventDefault();
                gameState.wasdActive.d = false;
                updateMovement();
            });
        }

        // 根据WASD状态更新移动
        function updateMovement() {
            gameState.player.velocityX = 0;
            gameState.player.velocityY = 0;
            
            if (gameState.wasdActive.w) {
                gameState.player.velocityY = -config.moveSpeed;
            }
            if (gameState.wasdActive.s) {
                gameState.player.velocityY = config.moveSpeed;
            }
            if (gameState.wasdActive.a) {
                gameState.player.velocityX = -config.moveSpeed;
            }
            if (gameState.wasdActive.d) {
                gameState.player.velocityX = config.moveSpeed;
            }
            
            gameState.isMoving = gameState.wasdActive.w || gameState.wasdActive.a || 
                                gameState.wasdActive.s || gameState.wasdActive.d;
        }

        // 设置键盘控制
        function setupKeyboardControls() {
            document.addEventListener('keydown', (e) => {
                switch(e.key.toLowerCase()) {
                    case 'w':
                        gameState.wasdActive.w = true;
                        updateMovement();
                        break;
                    case 'a':
                        gameState.wasdActive.a = true;
                        updateMovement();
                        break;
                    case 's':
                        gameState.wasdActive.s = true;
                        updateMovement();
                        break;
                    case 'd':
                        gameState.wasdActive.d = true;
                        updateMovement();
                        break;
                }
            });
            
            document.addEventListener('keyup', (e) => {
                switch(e.key.toLowerCase()) {
                    case 'w':
                        gameState.wasdActive.w = false;
                        updateMovement();
                        break;
                    case 'a':
                        gameState.wasdActive.a = false;
                        updateMovement();
                        break;
                    case 's':
                        gameState.wasdActive.s = false;
                        updateMovement();
                        break;
                    case 'd':
                        gameState.wasdActive.d = false;
                        updateMovement();
                        break;
                }
            });
        }

        // 放大视野
        function zoomIn() {
            const currentIndex = config.allowedZooms.indexOf(gameState.zoomLevel);
            if (currentIndex < config.allowedZooms.length - 1) {
                gameState.zoomLevel = config.allowedZooms[currentIndex + 1];
                updateDebugInfo();
            }
        }

        // 缩小视野
        function zoomOut() {
            const currentIndex = config.allowedZooms.indexOf(gameState.zoomLevel);
            if (currentIndex > 0) {
                gameState.zoomLevel = config.allowedZooms[currentIndex - 1];
                updateDebugInfo();
            }
        }

        // 切换网格显示
        function toggleGrid() {
            gameState.showGrid = !gameState.showGrid;
            gridToggle.textContent = `网格: ${gameState.showGrid ? '开' : '关'}`;
            gridToggle.classList.toggle('active', gameState.showGrid);
        }

        // 显示MOD管理器
        function showModManager() {
            modManager.style.display = 'flex';
            
            // 清空MOD列表
            modList.innerHTML = '';
            
            // 添加基础MOD
            const baseMods = [
                { id: 'natureMod', name: '自然扩展MOD' },
                { id: 'buildingMod', name: '建筑MOD' },
                { id: 'monsterMod', name: '怪物MOD' }
            ];
            
            // 添加已安装的MOD
            const allMods = [...baseMods, ...installedMods];
            
            // 为每个MOD创建UI元素
            allMods.forEach(mod => {
                const modItem = document.createElement('div');
                modItem.className = 'mod-item';
                
                const modName = document.createElement('div');
                modName.className = 'mod-name';
                modName.textContent = mod.name;
                
                const modToggle = document.createElement('label');
                modToggle.className = 'mod-toggle';
                
                const checkbox = document.createElement('input');
                checkbox.type = 'checkbox';
                checkbox.id = `${mod.id}Toggle`;
                checkbox.checked = gameState.mods[mod.id] || false;
                
                checkbox.addEventListener('change', () => {
                    gameState.mods[mod.id] = checkbox.checked;
                    if (modSystem[mod.id]) {
                        if (checkbox.checked) {
                            modSystem[mod.id].activate();
                        } else {
                            modSystem[mod.id].deactivate();
                        }
                    }
                });
                
                const slider = document.createElement('span');
                slider.className = 'mod-slider';
                
                modToggle.appendChild(checkbox);
                modToggle.appendChild(slider);
                
                modItem.appendChild(modName);
                modItem.appendChild(modToggle);
                
                modList.appendChild(modItem);
            });
        }

        // 隐藏MOD管理器
        function hideModManager() {
            modManager.style.display = 'none';
        }

        // 初始化世界列表
        function initWorldList() {
            worldList.innerHTML = '';
            
            const worlds = memoryStorage.getWorldList();
            
            if (worlds.length === 0) {
                const emptyMsg = document.createElement('div');
                emptyMsg.className = 'world-item';
                emptyMsg.textContent = '暂无存档';
                emptyMsg.style.color = '#888';
                worldList.appendChild(emptyMsg);
                return;
            }
            
            worlds.forEach(world => {
                const worldItem = document.createElement('div');
                worldItem.className = 'world-item';
                worldItem.textContent = world.name;
                worldItem.dataset.seed = world.seed;
                
                worldItem.addEventListener('click', () => {
                    seedInput.value = world.seed;
                });
                
                worldList.appendChild(worldItem);
            });
        }

        // 创建新世界
        function createNewWorld() {
            const seed = seedInput.value.trim() || Date.now();
            gameState.worldSeed = parseInt(seed) || seed;
            
            gameState.worldName = `世界_${Math.abs(gameState.worldSeed).toString(36).substring(0, 6)}`;
            worldNameElement.textContent = gameState.worldName;
            
            gameState.player.x = 0;
            gameState.player.y = 0;
            gameState.player.velocityX = 0;
            gameState.player.velocityY = 0;
            gameState.chunks = {};
            gameState.buildings = {};
            gameState.inventory.selectedItem = null;
            gameState.zoomLevel = config.defaultZoom;
            
            mainMenu.style.display = 'none';
            gameScreen.style.display = 'block';
            
            init();
        }

        // 加载世界
        function loadWorld() {
            const selectedWorldName = seedInput.value.trim();
            
            if (!selectedWorldName) {
                alert("请选择一个世界");
                return;
            }
            
            const worldData = memoryStorage.loadWorld(selectedWorldName);
            
            if (!worldData) {
                alert("世界不存在");
                return;
            }
            
            gameState.worldName = worldData.name;
            gameState.worldSeed = worldData.seed;
            worldNameElement.textContent = gameState.worldName;
            
            gameState.player.x = worldData.player.x || 0;
            gameState.player.y = worldData.player.y || 0;
            gameState.player.velocityX = 0;
            gameState.player.velocityY = 0;
            gameState.chunks = worldData.chunks || {};
            gameState.buildings = worldData.buildings || {};
            gameState.inventory.selectedItem = null;
            gameState.zoomLevel = config.defaultZoom;
            
            mainMenu.style.display = 'none';
            gameScreen.style.display = 'block';
            
            init();
        }

        // 保存世界
        function saveWorld() {
            memoryStorage.saveWorld({
                name: gameState.worldName,
                seed: gameState.worldSeed,
                player: {
                    x: gameState.player.x,
                    y: gameState.player.y
                },
                chunks: gameState.chunks,
                buildings: gameState.buildings
            });
            
            initWorldList();
            
            alert(`世界 "${gameState.worldName}" 已保存`);
        }

        // 显示主菜单
        function showMainMenu() {
            gameScreen.style.display = 'none';
            mainMenu.style.display = 'flex';
        }

        // 切换背包显示
        function toggleInventory() {
            gameState.isInventoryOpen = !gameState.isInventoryOpen;
            inventory.style.display = gameState.isInventoryOpen ? 'grid' : 'none';
        }

        // 选择快捷栏格子
        function selectHotbarSlot(index) {
            document.querySelectorAll('.hotbarSlot').forEach(slot => {
                slot.classList.remove('active');
            });
            
            const slot = document.querySelector(`.hotbarSlot[data-index="${index}"]`);
            if (slot) {
                slot.classList.add('active');
                gameState.inventory.selectedSlot = index;
            }
        }

        // 生成初始区块
        function generateInitialChunks() {
            const centerChunkX = Math.floor(gameState.player.x / (config.chunkSize * config.tileSize));
            const centerChunkY = Math.floor(gameState.player.y / (config.chunkSize * config.tileSize));
            
            for (let x = -config.renderDistance; x <= config.renderDistance; x++) {
                for (let y = -config.renderDistance; y <= config.renderDistance; y++) {
                    const chunkX = centerChunkX + x;
                    const chunkY = centerChunkY + y;
                    generateChunk(chunkX, chunkY);
                }
            }
        }

        // 改进的噪声函数 - 产生更自然的生物群系
        function improvedNoise(x, y, seed) {
            // 使用分形噪声来产生更自然的边界
            let value = 0;
            let amplitude = 1;
            let frequency = 0.01;
            let maxValue = 0;
            
            // 多层噪声叠加
            for (let i = 0; i < 3; i++) {
                value += amplitude * simplexNoise2D(x * frequency, y * frequency, seed);
                maxValue += amplitude;
                amplitude *= 0.5;
                frequency *= 2;
            }
            
            // 归一化到[-1, 1]
            value = value / maxValue;
            
            return value;
        }

        // 优化的2D噪声函数
        function simplexNoise2D(x, y, seed) {
            const random = (x, y) => {
                const value = Math.sin(x * 12.9898 + y * 78.233 + seed) * 43758.5453;
                return value - Math.floor(value);
            };
            
            const iX = Math.floor(x);
            const iY = Math.floor(y);
            const fX = x - iX;
            const fY = y - iY;
            
            const n0 = random(iX, iY);
            const n1 = random(iX + 1, iY);
            const n2 = random(iX, iY + 1);
            const n3 = random(iX + 1, iY + 1);
            
            const u = fX * fX * (3.0 - 2.0 * fX);
            const v = fY * fY * (3.0 - 2.0 * fY);
            
            return n0 * (1 - u) * (1 - v) +
                   n1 * u * (1 - v) +
                   n2 * (1 - u) * v +
                   n3 * u * v;
        }

        // 检查位置是否被建筑占据
        function isPositionOccupied(worldX, worldY, buildingType) {
            const buildingKey = `${worldX},${worldY}`;
            
            // 如果该位置已有建筑
            if (gameState.buildings[buildingKey]) {
                return true;
            }
            
            // 对于树，需要检查上方位置是否也被占用
            if (buildingType === BUILDINGS.TREE) {
                const aboveKey = `${worldX},${worldY - 1}`;
                if (gameState.buildings[aboveKey]) {
                    return true;
                }
            }
            
            return false;
        }

        // 在指定位置生成建筑
        function generateBuilding(worldX, worldY, buildingType) {
            const buildingKey = `${worldX},${worldY}`;
            
            // 检查位置是否可用
            if (isPositionOccupied(worldX, worldY, buildingType)) {
                return false;
            }
            
            // 创建建筑
            gameState.buildings[buildingKey] = {
                type: buildingType.name,
                x: worldX,
                y: worldY,
                width: buildingType.width,
                height: buildingType.height,
                hasCollision: buildingType.hasCollision,
                collisionHeight: buildingType.collisionHeight || buildingType.height
            };
            
            // 对于树，需要标记上方位置也被占用
            if (buildingType === BUILDINGS.TREE) {
                const aboveKey = `${worldX},${worldY - 1}`;
                gameState.buildings[aboveKey] = {
                    type: 'tree_top',
                    x: worldX,
                    y: worldY - 1,
                    width: 1,
                    height: 1,
                    hasCollision: false
                };
            }
            
            return true;
        }

        // 生成区块 - 修复地形生成
        function generateChunk(chunkX, chunkY) {
            const chunkKey = `${chunkX},${chunkY}`;
            
            if (!gameState.chunks[chunkKey]) {
                gameState.chunks[chunkKey] = {
                    x: chunkX,
                    y: chunkY,
                    tiles: []
                };
                
                // 为每个方块生成生物群系
                for (let x = 0; x < config.chunkSize; x++) {
                    gameState.chunks[chunkKey].tiles[x] = [];
                    for (let y = 0; y < config.chunkSize; y++) {
                        const worldX = chunkX * config.chunkSize + x;
                        const worldY = chunkY * config.chunkSize + y;
                        
                        // 使用改进的噪声函数生成生物群系
                        const noiseValue = improvedNoise(worldX * 0.01, worldY * 0.01, gameState.worldSeed);
                        
                        let biome;
                        if (gameState.mods.natureMod) {
                            biome = modSystem.natureMod.modifyBiomeGeneration(noiseValue);
                        } else {
                            // 默认生物群系生成
                            if (noiseValue < -0.4) {
                                biome = 'water';
                            } else if (noiseValue < -0.1) {
                                biome = 'sand';
                            } else if (noiseValue < 0.3) {
                                biome = 'grass';
                            } else if (noiseValue < 0.6) {
                                biome = 'forest';
                            } else {
                                biome = 'mountain';
                            }
                        }
                        
                        gameState.chunks[chunkKey].tiles[x][y] = {
                            type: 'ground',
                            biome: biome
                        };
                        
                        // 在合适的生物群系中生成建筑
                        if ((biome === 'grass' || biome === 'forest') && Math.random() < config.buildingDensity) {
                            // 生成草
                            if (Math.random() < BUILDINGS.GRASS.spawnChances[biome]) {
                                generateBuilding(worldX, worldY, BUILDINGS.GRASS);
                            }
                            
                            // 生成树
                            if (Math.random() < BUILDINGS.TREE.spawnChances[biome]) {
                                generateBuilding(worldX, worldY, BUILDINGS.TREE);
                            }
                        }
                        
                        // 生成水晶矿（如果MOD已加载）
                        if (biome === 'mountain' && gameState.mods.crystalMod && Math.random() < config.buildingDensity) {
                            if (BUILDINGS.CRYSTAL && Math.random() < BUILDINGS.CRYSTAL.spawnChances[biome]) {
                                generateBuilding(worldX, worldY, BUILDINGS.CRYSTAL);
                            }
                        }
                    }
                }
            }
        }

        // 检查玩家是否与建筑碰撞
        function checkCollision(playerX, playerY) {
            // 将玩家位置转换为世界坐标
            const playerWorldX = Math.floor(playerX / config.tileSize);
            const playerWorldY = Math.floor(playerY / config.tileSize);
            
            // 检查玩家所在位置是否有碰撞性建筑
            const buildingKey = `${playerWorldX},${playerWorldY}`;
            const building = gameState.buildings[buildingKey];
            
            if (building && building.hasCollision) {
                return true;
            }
            
            return false;
        }

        // 更新游戏状态
        function update() {
            // 保存玩家当前位置
            const oldX = gameState.player.x;
            const oldY = gameState.player.y;
            
            // 尝试移动玩家
            gameState.player.x += gameState.player.velocityX;
            gameState.player.y += gameState.player.velocityY;
            
            // 检查碰撞
            if (checkCollision(gameState.player.x, gameState.player.y)) {
                // 如果发生碰撞，恢复玩家位置
                gameState.player.x = oldX;
                gameState.player.y = oldY;
            }
            
            updateChunks();
            updateDebugInfo();
        }

        // 更新渲染的区块
        function updateChunks() {
            const centerChunkX = Math.floor(gameState.player.x / (config.chunkSize * config.tileSize));
            const centerChunkY = Math.floor(gameState.player.y / (config.chunkSize * config.tileSize));
            
            // 生成新区块
            for (let x = -config.renderDistance; x <= config.renderDistance; x++) {
                for (let y = -config.renderDistance; y <= config.renderDistance; y++) {
                    const chunkX = centerChunkX + x;
                    const chunkY = centerChunkY + y;
                    generateChunk(chunkX, chunkY);
                }
            }
        }

        // 更新调试信息
        function updateDebugInfo() {
            const playerWorldX = Math.floor(gameState.player.x / config.tileSize);
            const playerWorldY = Math.floor(gameState.player.y / config.tileSize);
            const chunkX = Math.floor(playerWorldX / config.chunkSize);
            const chunkY = Math.floor(playerWorldY / config.chunkSize);
            
            let biomeName = '未知';
            const chunk = gameState.chunks[`${chunkX},${chunkY}`];
            if (chunk) {
                const localX = playerWorldX % config.chunkSize;
                const localY = playerWorldY % config.chunkSize;
                if (chunk.tiles[localX] && chunk.tiles[localX][localY]) {
                    const biome = chunk.tiles[localX][localY].biome;
                    
                    // 如果有自然扩展MOD，使用MOD提供的名称
                    if (gameState.mods.natureMod) {
                        biomeName = modSystem.natureMod.getBiomeDisplayName(biome) || biome;
                    } else {
                        biomeName = 
                            biome === 'water' ? '水域' :
                            biome === 'sand' ? '沙滩' :
                            biome === 'grass' ? '平原' :
                            biome === 'forest' ? '森林' :
                            biome === 'mountain' ? '山地' : '未知';
                    }
                }
            }
            
            debugInfo.innerHTML = `
                <div>坐标: (${playerWorldX}, ${playerWorldY})</div>
                <div>区块: (${chunkX}, ${chunkY})</div>
                <div>生物群系: ${biomeName}</div>
                <div>缩放: ${Math.round(gameState.zoomLevel * 100)}%</div>
            `;
        }

        // 渲染游戏
        function render() {
            // 清空画布
            ctx.fillStyle = '#000';
            ctx.fillRect(0, 0, canvas.width, canvas.height);
            
            const offsetX = canvas.width / 2 - gameState.player.x * gameState.zoomLevel;
            const offsetY = canvas.height / 2 - gameState.player.y * gameState.zoomLevel;
            
            // 渲染地形
            for (const chunkKey in gameState.chunks) {
                const chunk = gameState.chunks[chunkKey];
                
                for (let x = 0; x < config.chunkSize; x++) {
                    for (let y = 0; y < config.chunkSize; y++) {
                        const tile = chunk.tiles[x][y];
                        const worldX = (chunk.x * config.chunkSize + x) * config.tileSize;
                        const worldY = (chunk.y * config.chunkSize + y) * config.tileSize;
                        
                        // 计算屏幕坐标并取整
                        const screenX = Math.round(worldX * gameState.zoomLevel + offsetX);
                        const screenY = Math.round(worldY * gameState.zoomLevel + offsetY);
                        
                        const tileSize = Math.round(config.tileSize * gameState.zoomLevel);
                        
                        // 如果方块在屏幕外，跳过渲染
                        if (screenX + tileSize < 0 || 
                            screenX > canvas.width ||
                            screenY + tileSize < 0 || 
                            screenY > canvas.height) {
                            continue;
                        }
                        
                        let color;
                        switch (tile.biome) {
                            case 'water': color = '#004466'; break;
                            case 'sand': color = '#666600'; break;
                            case 'grass': color = '#006600'; break;
                            case 'forest': color = '#004400'; break;
                            case 'mountain': color = '#333333'; break;
                            case 'snow': color = '#ffffff'; break;
                            case 'desert': color = '#ffcc66'; break;
                            case 'jungle': color = '#009900'; break;
                            default: color = '#333333';
                        }
                        
                        ctx.fillStyle = color;
                        ctx.fillRect(screenX, screenY, tileSize, tileSize);
                        
                        // 如果开启网格，绘制方块分界线
                        if (gameState.showGrid) {
                            ctx.strokeStyle = 'rgba(255, 255, 255, 0.2)';
                            ctx.lineWidth = 1;
                            ctx.strokeRect(screenX, screenY, tileSize, tileSize);
                        }
                    }
                }
            }
            
            // 渲染建筑
            for (const buildingKey in gameState.buildings) {
                const building = gameState.buildings[buildingKey];
                const worldX = building.x * config.tileSize;
                const worldY = building.y * config.tileSize;
                
                // 计算屏幕坐标
                const screenX = Math.round(worldX * gameState.zoomLevel + offsetX);
                const screenY = Math.round(worldY * gameState.zoomLevel + offsetY);
                const tileSize = Math.round(config.tileSize * gameState.zoomLevel);
                
                // 如果建筑在屏幕外，跳过渲染
                if (screenX + tileSize * building.width < 0 || 
                    screenX > canvas.width ||
                    screenY + tileSize * building.height < 0 || 
                    screenY > canvas.height) {
                    continue;
                }
                
                // 根据建筑类型渲染
                if (building.type === BUILDINGS.GRASS.name) {
                    // 渲染草
                    const emojiSize = Math.round(tileSize * 0.8);
                    ctx.font = `${emojiSize}px Arial`;
                    ctx.fillStyle = '#ccc';
                    ctx.textAlign = 'center';
                    ctx.textBaseline = 'middle';
                    ctx.fillText(BUILDINGS.GRASS.emoji, screenX + tileSize/2, screenY + tileSize/2);
                } else if (building.type === BUILDINGS.TREE.name || building.type === 'tree_top') {
                    // 渲染树 - 只有下方方块才渲染
                    if (building.type === BUILDINGS.TREE.name) {
                        const emojiSize = Math.round(tileSize * 1.6); // 树的大小是普通方块的1.6倍
                        ctx.font = `${emojiSize}px Arial`;
                        ctx.fillStyle = '#ccc';
                        ctx.textAlign = 'center';
                        ctx.textBaseline = 'middle';
                        // 树的emoji位置稍微向上偏移，使其看起来占据两个方块
                        ctx.fillText(BUILDINGS.TREE.emoji, screenX + tileSize/2, screenY + tileSize/2 - tileSize/2);
                    }
                } else if (building.type === 'crystal') {
                    // 渲染水晶矿
                    const emojiSize = Math.round(tileSize * 1.0);
                    ctx.font = `${emojiSize}px Arial`;
                    ctx.fillStyle = '#9be7ff';
                    ctx.textAlign = 'center';
                    ctx.textBaseline = 'middle';
                    ctx.fillText('💎', screenX + tileSize/2, screenY + tileSize/2);
                }
            }
            
            // 渲染玩家
            const playerSize = Math.round(20 * gameState.zoomLevel);
            ctx.font = `${playerSize}px Arial`;
            ctx.fillStyle = '#ccc';
            ctx.textAlign = 'center';
            ctx.textBaseline = 'middle';
            ctx.fillText('😎', canvas.width / 2, canvas.height / 2);
        }

        // 游戏主循环
        function gameLoop() {
            update();
            render();
            requestAnimationFrame(gameLoop);
        }
        
        // 初始化世界列表
        initWorldList();
        
        // 添加示例世界
        memoryStorage.saveWorld({ name: "示例世界1", seed: 12345, player: { x: 0, y: 0 }, chunks: {}, buildings: {} });
        memoryStorage.saveWorld({ name: "示例世界2", seed: 67890, player: { x: 0, y: 0 }, chunks: {}, buildings: {} });
        initWorldList();
        
        // 设置事件监听器
        setupEventListeners();
    </script>
</body>
</html>